"use strict";

/**
 * @ngdoc service
 * @name myAppApp.httpInterceptor
 * @description
 * # httpInterceptor
 * Service in the jgappApp.
 */
angular
  .module("jgappApp")
  .factory("httpInterceptor", function($q,openApi) {
    console.log("http loader was controlled here");
    var count = 0;
    return {
      request: function(config) {
        config.timeout = 10000;
        config.data = config.data || {};
        if (config.url.indexOf(openApi.ip) > -1) {
          if (!config.data.noloader && !config.noloader) {
            if(count === 0){
              console.log(config.url);
              NativeUtil.toggleProgressDialog(1);
              console.log("open");
            }
            count++;
          }
         var sign;
         var signStr=NativeUtil.getSignStr();
          if (config.url.indexOf("?") > -1) {
            sign = "&" + signStr;
          } else {
            sign = "?" + signStr;
          }
          config.url += sign;
        }
        return config;
      },
      response: function(response) {
        var config=response.config
        if (config&&config.url.indexOf(openApi.ip) > -1) {
          if (!config.data.noloader && !config.noloader) {
              count--;
            if(count === 0){
              NativeUtil.toggleProgressDialog(0);
                console.log("close");
            }
          }
          console.log(count);
        }
        var headers = response.headers();
        if (headers.sessionexpired === "true") {
          response.data = {};
          response.data.logout = 1;
          // $location.path("login/login")
        }
        return response || $q.when(response);
      },
      responseError: function(rejection) {
        var config=rejection.config
        if (config&&config.url.indexOf(openApi.ip) > -1) {
          if (!config.data.noloader && !config.noloader) {
              count--;
            if(count === 0){
              NativeUtil.toggleProgressDialog(0);
              console.log("close");
            }
            console.log(count);
          }

        }
        return $q.reject(rejection);
      }
    };
  });
